package com.bw.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.bw.domain.*;
import com.bw.service.*;
import com.bw.utils.R;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwt;
import io.jsonwebtoken.Jwts;
import io.swagger.models.auth.In;
import org.apache.http.protocol.HTTP;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author bobo棒
 * @date 2024年07月08日 15:34
 */

@RestController
@RequestMapping("comment")
public class CommentController {

    @Autowired
    CommentService commentService;
    @Autowired
    ChannelService channelService;
    @Autowired
    ReplyService replyService;
    @Autowired
    RedissonClient redissonClient;
    @Autowired
    UserService userService;


    /**
     * 添加评论
     *
     * @param comment
     * @param request
     * @return
     */
    @PostMapping("add")
    public R add(@RequestBody Comment comment, HttpServletRequest request) {
        //获取锁
        RLock lock = redissonClient.getLock("lock:" + comment.getChannelId());
        try {
            //5 等待5秒获取锁.
            //10.   10秒后需要释放锁
            boolean b1 = lock.tryLock(5, 10, TimeUnit.SECONDS);
            if (b1) {
                //评论时间
                comment.setCreateTime(new Date());
                //获取评论人
                String token = request.getHeader("token");
                if (token == null || token.equals("")) {
                    return R.error("请先登录");
                }
                Claims claims = Jwts.parser().setSigningKey("BW".getBytes()).parseClaimsJws(token).getBody();
                Integer id = claims.get("id", Integer.class);

                User dbUser = userService.getById(id);
                if(dbUser==null){
                    return R.error("非注册用户不能评论");
                }
                comment.setUserId(id);
                boolean b = commentService.save(comment);
                //更新评论数量
                if (b) {
                    channelService.updateCommentNum(comment.getChannelId());
                }
                return b ? R.success() : R.error();
            }
            return R.error("系统繁忙稍稍再试");

        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            //释放锁
            lock.unlock();
        }

    }


    @RequestMapping("getCommentByChannelId/{id}")
    public R getCommentsByChannelId(@PathVariable("id") Integer id) {

        List<Comment> list = commentService.getCommentsByChannelId(id);
        return R.success(list);
    }

    /**
     * 添加回复
     *
     * @param reply
     * @param request
     * @return
     */
    @PostMapping("addReply")
    public R addReply(@RequestBody Reply reply, HttpServletRequest request) {
        //获取锁
        RLock lock = redissonClient.getLock("lock:" + reply.getChannelId());
        try {
            //5 等待5秒获取锁.
            //10.   10秒后需要释放锁
            boolean b1 = lock.tryLock(5, 10, TimeUnit.SECONDS);
            if (b1) {
                //回复时间
                reply.setCreateTime(new Date());
                //获取回复人
                String token = request.getHeader("token");
                if (token == null || token.equals("")) {
                    return R.error("请先登录");
                }
                Claims claims = Jwts.parser().setSigningKey("BW".getBytes()).parseClaimsJws(token).getBody();
                Integer id = claims.get("id", Integer.class);
                User dbUser = userService.getById(id);
                if(dbUser==null){
                    return R.error("非注册用户不能评论");
                }

                reply.setUserId(id);
                boolean b = replyService.save(reply);
                if(b){
                    channelService.updateCommentNum(reply.getChannelId());
                }
                return b ? R.success() : R.error();

            }


        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //释放锁
            lock.unlock();
        }

        return R.error("系统繁忙稍稍再试");
    }

}
